<?php

class FaqInstall
{
	private $_config = array(
		'name' => 'faq',
		'title' => 'FAQ module',
		'dependencies' => array(
			'editor',
			'languages' => array(
				'{{faq}}' => array(
					'fields' => array(
						'question'=>'varchar(255) NOT NULL',
						'answer'=>'text NOT NULL',
					)
				)
			),
			'seo' => array(
				'rules' => array(
					'faq/default/index'=>array(
						'template'=>'faq',
						'model'=>'Faq',
						'path'=>'application.modules.faq.models.Faq'
					),
					'faq/default/view'=>array(
						'template'=>'faq/<question>',
						'model'=>'Faq',
						'path'=>'application.modules.faq.models.Faq'
					)
				)
			),
		),
		'import' => array(
			'application.modules.faq.FaqModule',
		)
	);
	public function config()
	{
		return $this->_config;
	}
	
	public function install()
	{
		$languages = Languages::model()->getLanguages();	

		foreach ($languages as $language)
		{
			foreach ($this->_config['dependencies']['languages']['{{faq}}']['fields'] as $field => $type)
			{
				$keys[] = $field.'_'.$language['code'];
				$values[] = ':'.$field.'_'.$language['code'];
				$fields[] = "`".$field."_".$language['code']."` ".$type.",";
			}
		}

		$sql = "DROP TABLE IF EXISTS {{faq}};";
		Yii::app()->db->createCommand($sql)->execute();

		$sql="
	CREATE TABLE IF NOT EXISTS {{faq}} (
	  `id` int(11) NOT NULL AUTO_INCREMENT,
	  `active` tinyint(1) NOT NULL DEFAULT '1',
	  `sorter` tinyint(4) NOT NULL,";
		$sql .= implode("", $fields);
		$sql .= "
	  PRIMARY KEY (`id`)
	) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;";
		Yii::app()->db->createCommand($sql)->execute();


		$sql="INSERT INTO {{faq}} (active, sorter, ".implode(', ', $keys).") VALUES (:active, :sorter, ".implode(', ', $values).");";
		$command = Yii::app()->db->createCommand($sql);

		$command->bindValue(":active", 1, PDO::PARAM_INT);
		$command->bindValue(":sorter", 1, PDO::PARAM_INT);
		foreach ($languages as $language)
		{
			$command->bindValue(":question_".$language['code'], Yii::t('FaqModule.install', 'На чем написан OpenPromo Site?', array(), null, $language['code']), PDO::PARAM_STR);
			$command->bindValue(":answer_".$language['code'], Yii::t('FaqModule.install', 'OpenPromo Site написан на фреймворке Yii.', array(), null, $language['code']), PDO::PARAM_STR);
		}
		$command->execute();

		$command->bindValue(":active", 1, PDO::PARAM_INT);
		$command->bindValue(":sorter", 2, PDO::PARAM_INT);
		foreach ($languages as $language)
		{
			$command->bindValue(":question_".$language['code'], Yii::t('FaqModule.install', 'Что такое OpenPromoSite?', array(), null, $language['code']), PDO::PARAM_STR);
			$command->bindValue(":answer_".$language['code'], Yii::t('FaqModule.install', 'OpenPromoSite это сайт-визитка с открытым кодом.', array(), null, $language['code']), PDO::PARAM_STR);
		}
		$command->execute();
	}

	public function uninstall()
	{
		Yii::app()->db->createCommand()->dropTable('{{faq}}');
	}

}